package com.youkeda.kafka.study.control;

import com.alibaba.fastjson.JSON;
import com.youkeda.kafka.study.model.Student;
import com.youkeda.kafka.study.util.NameUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
public class SenderControl {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private static final int[] DATE_RANGE = {-1, 0, 1};

    @PostConstruct
    public void init() {
        System.out.println("begin send messages.");
    }

    @GetMapping("/app/send")
    @ResponseBody
    public List<Student> sendData() {
        List<Student> ss = new ArrayList<>();

        // 当天前后三天
        for (int dateRange : DATE_RANGE) {
            LocalDate date = LocalDate.now().plusDays(dateRange);
            Random random = new Random();
            // 每天随机一半以上人学习
            int half = NameUtil.getLength() / 2;
            int odd = NameUtil.getLength() - half;
            int studyCount = random.nextInt(odd) + half;

            // 取得一批随机名字
            List<String> names = NameUtil.shuffle(studyCount);

            int s = 0;
            while (s < studyCount) {
                String name = names.get(s);
                Student student = buildData(name, date);
                //System.out.println(JSON.toJSONString(student));

                s++;
                kafkaTemplate.send("studyData", name, JSON.toJSONString(student));
                ss.add(student);
            }
        }

        return ss;
    }

    private Student buildData(String name, LocalDate date) {
        Student student = new Student();
        Random random = new Random();
        student.setName(name);
        student.setStdudyDate(date);
        // 随机学习 10-40 分钟
        student.setDuration(random.nextInt(30 * 60) + 10 * 60);
        // 随机学习 1-10 章
        student.setSections(random.nextInt(10) + 1);
        // 随机 100-1100 行代码
        student.setCodeRows(random.nextInt(1000) + 100);

        return student;
    }
}
